package com.grwx.omc.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.grwx.omc.admin.dao.SysOrgMapper;
import com.grwx.omc.admin.entity.SysLookupType;
import com.grwx.omc.admin.entity.SysOrg;
import com.grwx.omc.admin.service.ISysOrgService;
import com.grwx.omc.constant.Constant;
import com.grwx.omc.exception.BusinessException;
import com.grwx.omc.exception.ValidationException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class SysOrgServiceImpl extends ServiceImpl<SysOrgMapper, SysOrg>
        implements ISysOrgService {

    @Resource
    private SysOrgMapper sysOrgMapper;

    @Override
    public IPage<SysOrg> page(Page<SysOrg> page, SysOrg sysOrg) {
        return sysOrgMapper.pageList(page, sysOrg);
    }

    @Override
    public void addOrUpdate(SysOrg sysOrg) {
        if (StringUtils.isEmpty(sysOrg.getParentId())) {
            sysOrg.setParentId(Constant.LOOKUP_TYPE_ROOT_ID);
        }
        // 字典类型编码唯一性校验
        uniqueCheck(sysOrg);

        if (null == sysOrg.getId()) {
            sysOrg.preInsert();
            save(sysOrg);
        } else {
            sysOrg.preUpdate();
            updateById(sysOrg);
        }
    }

    /**
     * orgCode唯一校验
     * 规则：同一服务(parentId)下，字典类型不能重复
     * @param sysOrg
     */
    private void uniqueCheck(SysOrg sysOrg) {
        QueryWrapper<SysOrg> wrapper = new QueryWrapper<>();
        if (!ObjectUtils.isEmpty(sysOrg.getId())) {
            wrapper.ne("id", sysOrg.getId());
        }
        wrapper.and(Wrapper ->
                Wrapper.eq("org_code", sysOrg.getOrgCode()).or().eq("org_name", sysOrg.getOrgName()));
        List<SysOrg> existLookupType = list(wrapper);
        if (!ObjectUtils.isEmpty(existLookupType)) {
            throw new ValidationException("omc.admin.org.E001");
        }
    }




    @Override
    public void del(Long[] ids) {
        // TODO: 2020/5/13 删除校验

        // TODO: 2020/5/13 级联删除、校验

    }
}
